import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import "./course.css";

function CourseNew(props) {
    const formRef = useRef(null);
    const navigate = useNavigate();
    const [isBusy, setBusy] = useState(false);
    const [actionError, setActionError] = useState(null);

    const saveAction = async () => {
        if (!formRef.current) return;
        const elements = formRef.current.elements;
        let data = {
            cou_sn: null,
            cou_no: elements.cou_no.value,
            cou_name: elements.cou_name.value,
            credit: elements.credit.value ? parseFloat(elements.credit.value) : null,
            hours: elements.hours.value ? parseInt(elements.hours.value) : null,
        };
        console.log('提交数据', data);
        try {
            setBusy(true);
            let response = await fetch("/api/course", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify(data),
            });
            if (!response.ok) {
                let errorText = await response.text();
                setActionError(errorText);
                return;
            }
            navigate("/course/list");
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>新建课程</h3>
            </div>
            <div className="paper-body">
                <form ref={formRef}>
                    <div className="field">
                        <label>课程号: </label>
                        <input type="text" name="cou_no" required />
                    </div>
                    <div className="field">
                        <label>课程名称: </label>
                        <input type="text" name="cou_name" required />
                    </div>
                    <div className="field">
                        <label>学分: </label>
                        <input type="number" name="credit" step="0.1" required />
                    </div>
                    <div className="field">
                        <label>学时: </label>
                        <input type="number" name="hours" required />
                    </div>
                </form>
                {actionError && <pre className="error">{actionError}</pre>}
            </div>
            <div className="paper-footer">
                <div className="btns">
                    <button className="btn" onClick={() => navigate("/course/list")}>
                        返回
                    </button>
                    <button className="btn" onClick={saveAction} disabled={isBusy}>
                        保存
                    </button>
                </div>
            </div>
        </div>
    );
}

export default CourseNew; 